package com.jgsu.farm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jgsu.farm.entity.BiologyCategory;
import com.jgsu.farm.exception.DataAddException;
import com.jgsu.farm.exception.DataNotExistException;
import com.jgsu.farm.mapper.BiologyCategoryMapper;
import com.jgsu.farm.mapper.sql.BiologyMapperSql;
import com.jgsu.farm.service.BiologyCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BiologyCategoryServiceImpl implements BiologyCategoryService {
    @Autowired
    BiologyMapperSql biologyMapperSql;
    @Autowired
    BiologyCategoryMapper biologyCategoryMapper;

    @Override
    public void addBiologyCategory(BiologyCategory biologyCategory) {
        // 1. 先查询数据库中是否存在该植物类属
        BiologyCategory one = biologyCategoryMapper.selectOne(biologyCategory);
        // 如果数据库中不存在该表，则添加入数据库
        if (one == null) {
            biologyCategoryMapper.insert(biologyCategory);
        } else {
            throw new DataAddException("604", "BIO表数据添加异常");
        }
    }


    /**
     * 分页查询所有植物分类表
     */
    @Override
    public PageInfo<BiologyCategory> findListBiologyCategory(int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        List<BiologyCategory> biologyCategories = biologyCategoryMapper.selectAll();
        PageInfo<BiologyCategory> pageInfoUserList = new PageInfo<BiologyCategory>(biologyCategories);
        return pageInfoUserList;
    }


    /**
     * 删除某一植物分类的信息
     */
    @Override
    public void deleteBioById(Integer bioid) {
        Integer i = biologyCategoryMapper.deleteByPrimaryKey(bioid);
        if (i == 0 || i == null) {
            throw new DataNotExistException("603", "不存在该id,植物分类删除失败");
        }
    }

    /**
     * 更新某一植物分类的信息
     */
    @Override
    public void updateBiologyCategory(BiologyCategory biologyCategory) {
        // 先判段数据库中是否存在该植物分类
        BiologyCategory biologyCategoryId = biologyCategoryMapper.selectByPrimaryKey(biologyCategory.getBioid());
        // 如果数据库中存在该数据
        if (biologyCategoryId != null) {
            biologyCategoryMapper.updateByPrimaryKey(biologyCategory);
        } else {
            throw new DataNotExistException("603", "植物分类数据更新失败，不存在相应植物分类id");
        }
    }


    @Override
    public int findBioId(Integer bioid) {
        return biologyMapperSql.selectById(bioid);
    }
}
